package com.sihan.framework.etm.service.impl;

import com.framework.mybatis.Condition;
import com.sihan.framework.etm.common.AppConfiguration;
import com.sihan.framework.etm.common.util.QuantityUtils;
import com.sihan.framework.etm.entity.baseData.DeviceModel;
import com.sihan.framework.etm.mapper.baseData.DeviceMapper;
import com.sihan.framework.etm.service.DeviceComputer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Map;

@Service
public class DeviceComputerImpl implements DeviceComputer {

    @Autowired
    private AppConfiguration appConfig;

    @Autowired
    private DeviceMapper deviceMapper;

    @Override
    public BigDecimal calculateAndUpdateVoltage(Map deviceData) {
        BigDecimal electricity = null;

        if (deviceData.get("code") != null && deviceData.get("code").equals(16385)) {
            BC20:
            {
                DeviceModel deviceInfo = deviceMapper.selectOne(new Condition<>().eq("communication_code", deviceData.get("deviceID").toString()).eq("is_delete", 0));
                if (deviceInfo == null) {
                    break BC20;
                }
                Integer sendCount = (Integer) deviceData.get("count");
                Integer m = appConfig.getVoltageCount();
                Integer n = appConfig.getVoltageWaitDays();
                LocalDate now = LocalDate.now();
                LocalDate existSendDate = null == deviceInfo.getSendNewTime() ? now :
                        deviceInfo.getSendNewTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                Long days = now.toEpochDay() - existSendDate.toEpochDay();
                BigDecimal a = new BigDecimal(m).divide(new BigDecimal(n), 3, RoundingMode.HALF_UP);
                BigDecimal x = new BigDecimal(sendCount).divide(new BigDecimal(4), 3, RoundingMode.HALF_UP);
                electricity = (new BigDecimal(m).subtract(x).subtract(
                        new BigDecimal(days.intValue()).multiply(a))).divide(new BigDecimal(m), 3, RoundingMode.HALF_UP).multiply(new BigDecimal(100));
            }
        } else if (deviceData.get("type") != null && deviceData.get("type").equals(4000)) {
            RTK:
            {
                DeviceModel deviceInfo = deviceMapper.selectOne(new Condition<>().eq("communication_code", deviceData.get("deviceID").toString()).eq("is_delete", 0));
                if (deviceInfo == null) {
                    break RTK;
                }
                electricity = QuantityUtils.formattedQuantity(new BigDecimal(deviceData.get("voltage").toString()));
                //electricity = BigDecimal.valueOf(Double.parseDouble(deviceData.get("voltage").toString())).divide(appConfig.getVoltageTotalRTK(), 2, RoundingMode.HALF_UP);
            }
        }

        return electricity;
    }
}
